package com.my.service.imp;

import com.my.dao.UserDao;
import com.my.dao.VipDao;
import com.my.pojo.User;
import com.my.pojo.Vip;
import com.my.service.IVipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VipServiceImpl implements IVipService {
    UserDao userDao;

    VipDao vipDao;

    @Autowired
    public void setVipDap(VipDao vipDao) {
        this.vipDao = vipDao;
    }

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public Vip getVip(Integer userId) {
        User user = userDao.getOne(userId);
        return user == null ? null : user.getVip();
    }

    @Override
    public Integer createVip(Integer userId) {
        User user = userDao.getOne(userId);
        if(user == null) {
            return -1;
        }

        if(user.getVip() != null) {
            return -2;
        }

        Vip vip = new Vip();
        vip.setStatus(0);

        Integer vipId = vipDao.save(vip).getVipId();
        if(vipId < 0) {
            return -3;
        }

        Vip res = new Vip();
        res.setVipId(vipId);
        return vipDao.save(res) == null ? -4 : 0;
    }

    @Override
    public Integer changeVip(Integer userId, Integer vipLevel) {
        User user = userDao.getOne(userId);
        if(user == null) {
            return -1;
        } else {
            Vip vip = user.getVip();
            if(vip == null) {
                return -2;
            } else {
                vip.setStatus(vipLevel);
                return vipDao.save(vip) == null ? -3 : 0;
            }
        }
    }

    @Override
    public Integer addMoney(Integer userId, Double count) {
        User user = userDao.getOne(userId);
        if(user == null) {
            return -1;
        } else {
            Vip vip = user.getVip();
            if(vip == null) {
                return -2;
            } else {
                vip.setMoney(vip.getMoney() + count);
                return vipDao.save(vip) == null ? -3 : 0;
            }
        }
    }

    @Override
    public Integer minusMoney(Integer userId, Double count) {
        User user = userDao.getOne(userId);
        if(user == null) {
            return -1;
        } else {
            Vip vip = user.getVip();
            if(vip == null) {
                return -2;
            } else {
                Double resMoney = vip.getMoney() - count;
                if(resMoney < 0) {
                    return -3;
                }
                vip.setMoney(vip.getMoney() - count);
                return vipDao.save(vip) == null ? -4 : 0;
            }
        }
    }


}
